<?php

// Load config.php
if ( file_exists( __DIR__.'/config.php' ) ) {
    include( __DIR__.'/config.php' );
}

// Parse URL
$s = !empty($_SERVER['HTTPS']) ? 's' : '' ;
$soc['url'] = parse_url("http{$s}://{$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']}");
$soc['dir'] = __DIR__;
file_put_contents($soc['dir'].'/debug.txt', "\n".date('Y-m-d H:i:s')."\n", FILE_APPEND);
//file_put_contents($soc['dir'].'/debug.txt', 'dir '.$soc['dir']."\n", FILE_APPEND);
/* fix for windows */
if ( DIRECTORY_SEPARATOR === '\\' ) {
    $soc['dir'] = strtolower( str_replace( '\\', '/', $soc['dir'] ) );
}
//file_put_contents($soc['dir'].'/debug.txt', 'fixed dir '.$soc['dir']."\n", FILE_APPEND);

// DocumentRoot заканчивающаяся на слеш. Это нужно исправить.
//file_put_contents($soc['dir'].'/debug.txt', 'DOCUMENT_ROOT '.$_SERVER['DOCUMENT_ROOT']."\n", FILE_APPEND);
$_SERVER['DOCUMENT_ROOT'] = rtrim( $_SERVER['DOCUMENT_ROOT'], '/' );

// Определяем папку относительно корня сайта, в которую установлена система
$soc['base_url'] = str_replace($_SERVER['DOCUMENT_ROOT'], '', $soc['dir']).'/';
//file_put_contents($soc['dir'].'/debug.txt', 'base_url '.$soc['base_url']."\n", FILE_APPEND);

$esc  = str_replace( '/', '\\/', $soc['base_url'] );
$soc['file'] = $soc['dir'].'/'.preg_replace( "/^{$esc}/", '', $soc['url']['path'] );

// Find and switch lang
if ( empty( $config['locale'] ) ) {
    foreach( glob( __DIR__.'/lang/*',  GLOB_ONLYDIR ) as $locale ) {
        if ( file_exists( "{$locale}/timezone.php" ) ) {
            include( "{$locale}/timezone.php" );
        }
        $locale = preg_replace( '/.*\//', '', $locale );
        $config['locale'] = $locale;
        setlocale( LC_ALL, $locale );
        $config['lang'] = substr( $locale, 0, 2 );
        break;
    }
    if ( empty( $config['lang'] ) ) {
        $config['lang'] = 'en';
    }
    soc_save_config();
}

// Set locale
if ( !empty( $config['locale'] ) ) {
    setlocale( LC_ALL, $config['locale'] );
    $file = __DIR__."/lang/{$config['locale']}/default.php";
    if ( file_exists( $file ) ) {
        include_once( $file );
    }  else {
        $translate[$config['locale']]['default'] = array();
    }
}

// Set timezone
if ( !empty( $config['timezone'] ) ) {
    date_default_timezone_set ( $config['timezone'] );
}

$soc['stage']  = 'init';
$soc['stages'] = array(
    'init' => array( 'disabled' => false, 'next' => 'work' ),
    'work' => array( 'disabled' => false, 'next' => ''     ),
    'api'  => array( 'disabled' => false, 'next' => ''     ),
);

$soc['urls'] = array();
$soc['urls']['^/api/$']  = 'api';

// Load modules
foreach( glob( __DIR__.'/mod/*.mod.php' ) as $module ) {
    include_once( $module );
}

// Sort urls and search triggered
krsort( $soc['urls'] );
foreach( $soc['urls'] as $url => $stage ) {
    // escape for regex
    $url = preg_replace( "/\//", "\\/", $url );
    if ( preg_match( "/{$url}/", $soc['url']['path'], $soc['url_matches'] ) ) {
        $soc['stage'] = $stage;
        break;
    }
}

// RUN
while ( !empty( $soc['stage'] ) ) {
    soc_do_stage( $soc['stage'] );
    $soc['stage'] = $soc['stages'][$soc['stage']]['next'];
}


/************ FUNCTIONS ************/

function __( $string, $context = 'default' ) {
    global $config, $translate;
    if ( !isset( $config['locale'] ) ) return $string;
    // Load lang file
    if ( !isset( $translate[$config['locale']][$context] ) ) {
        $file = __DIR__."/lang/{$config['locale']}/{$context}.php";
        if ( file_exists( $file ) ) {
            include_once( $file );
        } else {
            $translate[$config['locale']][$context] = array();
        }
    }
    // Translate
    if ( isset( $translate[$config['locale']][$context][$string] ) ) {
        return $translate[$config['locale']][$context][$string];
    } else {
        return $string;
    }
}

function soc_save_config() {
    global $config;
    @$r = file_put_contents( __DIR__.'/config.php', '<?php
$config = '.var_export($config, true).";\n", LOCK_EX);
    return $r;
}

function soc_do_stage($stage = '') {
    global $soc;
    if (!isset($soc['stages'][$stage]) || !empty($soc['stages'][$stage]['disabled'])) return;
    ksort($soc['stages'][$stage]);
    foreach ($soc['stages'][$stage] as $nice => $value) {
        # skip non numeric keys
        if (is_array($soc['stages'][$stage][$nice])) {
            foreach ( $soc['stages'][$stage][$nice] as $function => $enabled ) {
                if ( $enabled ) {
                    $function();
                }
            }
        }
    }
}

function soc_add_function($stage, $function, $nice = 10) {
    global $soc;
    $soc['stages'][$stage][$nice][$function] = true;
    if ( !isset( $soc['stages'][$stage]['next'] ) ) { $soc['stages'][$stage]['next'] = ''; } /* fix warning */
}

function soc_salt($count = 8) {
    $chars = '0123456789AaBbCcDdEeFfGgHhiJjKkLMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
    $strlen = strlen($chars)-1;
    $salt = '';
    while ($count--) {
        $salt .= $chars[rand(0,$strlen)];
    }
    return $salt;
}

function is_owner() {
    global $config;
    return 
      isset($_COOKIE['soc_login']) && 
      isset($_COOKIE['soc_password']) &&
      isset($config['logged'][$_COOKIE['soc_login']]) &&
      $config['logged'][$_COOKIE['soc_login']]['password'] === $_COOKIE['soc_password'];
}

function recurse_move($src,$dst) {
    $dir = opendir($src);
    if ( file_exists( $dst ) ) { mkdir( $dst, 0777, true ); }
    while( false !== ( $file = readdir($dir) ) ) {
        if ( ( $file != '.' ) && ( $file != '..' ) ) {
            if ( is_dir($src.'/'.$file) ) {
                recurse_move($src.'/'.$file, $dst.'/'.$file);
            } else {
                rename($src.'/'.$file, $dst.'/'.$file);
            }
        }
    }
    closedir($dir);
    rmdir($src);
}

function recurse_rm($src) /* bool */ {
    $dir = opendir($src);
    while( false !== ( $file = readdir($dir) ) ) {
        if ( ( $file != '.' ) && ( $file != '..' ) ) {
            if ( is_dir($src.'/'.$file) ) {
                recurse_rm($src.'/'.$file);
            } else {
                if (!unlink($src.'/'.$file)) {return false;}
            }
        }
    }
    closedir($dir);
    return rmdir($src);
}

function soc_readfile($file) {
    if (file_exists($file)) {
        
        $ext   = preg_replace( '/.*\./', '', $file );
        $mimes = array(
            'json' => 'application/json',
        );

        if ( isset( $mimes[$ext] ) ) {
            $mime = $mimes[$ext];
        } else {
            $mime = mime_content_type ( $file );
        }

        header('Content-Type: '.$mime);
        
        //header('Content-Transfer-Encoding: binary');
        //header('Expires: 0');
        //header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        //header('Pragma: public');
        //header('Content-Length: ' . filesize($file));
        @ob_clean();
        flush();
        
        if ( $fd = fopen( $file, 'rb' ) ) {
            while ( !feof( $fd ) ) {
              print fread( $fd, 1024 );
            }
            return fclose( $fd );
        } else {
            return false;
        }
        //return readfile($file); mem exhausted
    } else {
        return false;
    }
}

function soc_rsort( &$array, $field ) {
    if ( !is_array( $array ) || empty( $field ) ) return false;
    global $soc;
    $soc['soc_rsort'] = $field;
    return uasort( $array, function( $a, $b ) {
        global $soc;
        if ( !isset($a[ $soc['soc_rsort'] ]) || !isset($b[ $soc['soc_rsort'] ]) ) {
            return 0;
        }
        if ( $a[ $soc['soc_rsort'] ] === $b[ $soc['soc_rsort'] ] ) {
            return 0;
        } elseif ( $a[ $soc['soc_rsort'] ] < $b[ $soc['soc_rsort'] ] ) {
            return 1;
        } else {
            return -1;
        }
    } );
}
